package integral

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/app/business/api/internal/repository/integral"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizintegral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralwallet"
	"private-domain-overseas-service/tools/ent/hzintegralwalletrecord"
	"private-domain-overseas-service/tools/ent/predicate"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralWalletRecordListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 积分记录
func NewIntegralWalletRecordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralWalletRecordListLogic {
	return &IntegralWalletRecordListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralWalletRecordListLogic) IntegralWalletRecordList(req *types.IntegralWalletRecordRequest) (resp *types.IntegralWalletRecordResponse, err error) {
	integralWalletRecordDao := integral.NewIntegralWalletRecordDao(l.ctx, l.svcCtx)
	integralWalletDao := integral.NewIntegralWalletDao(l.ctx, l.svcCtx)

	// 获取用户id
	userId := common.JwtAuthUserId(l.ctx)
	// 定义百分之一初始值
	baiDecimal := decimal.NewFromInt32(100)

	// 构建查询积分记录条件
	integralWalletRecordConditions := make([]predicate.HzIntegralWalletRecord, 0)
	integralWalletRecordConditions = append(integralWalletRecordConditions, hzintegralwalletrecord.UserIDEQ(userId))
	switch req.Type {
	case bizintegral.Increase: //已获取
		integralWalletRecordConditions = append(integralWalletRecordConditions, hzintegralwalletrecord.RecordStatusEQ(bizintegral.Income))
	case bizintegral.Decrease: //已支出
		integralWalletRecordConditions = append(integralWalletRecordConditions, hzintegralwalletrecord.RecordStatusEQ(bizintegral.Disburse))
	}
	// 查询积分记录
	integralWalletRecordInfos, total, err := integralWalletRecordDao.ListIntegralWalletRecordByPage(integralWalletRecordConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("分页查询积分列表失：%v", err.Error()))
	}

	// 查询用户积分钱包
	integralWalletConditions := make([]predicate.HzIntegralWallet, 0)
	integralWalletConditions = append(integralWalletConditions, hzintegralwallet.UserIDEQ(userId))
	integralWalletInfo, err := integralWalletDao.IntegralWalletConditionsOnly(integralWalletConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询用户积分钱包失败：%v", err.Error()))
	}

	// 构建统计积分使用数量条件
	recordCountConditions := make([]predicate.HzIntegralWalletRecord, 0)
	recordCountConditions = append(recordCountConditions, hzintegralwalletrecord.UserIDEQ(userId))
	recordCountConditions = append(recordCountConditions, hzintegralwalletrecord.RecordStatusEQ(bizintegral.Disburse)) //支出

	//统计已使用的积分
	alreadyUse, _ := integralWalletRecordDao.WalletRecordConditionsSumField(recordCountConditions, hzintegralwalletrecord.FieldRecordAmount)

	//组装数据
	list := lo.Map(integralWalletRecordInfos, func(item *ent.HzIntegralWalletRecord, _ int) *types.IntegralWalletRecord {
		return &types.IntegralWalletRecord{
			Id:           int64(item.ID),
			Title:        item.RecordTitle,
			RecordStatus: item.RecordStatus,
			RecordType:   item.RecordType,
			RecordAmount: decimal.NewFromInt(item.RecordAmount).Div(baiDecimal).StringFixed(2),
			Balance:      decimal.NewFromInt(item.RecordActiveBalance).Div(baiDecimal).StringFixed(2),
			CreatedAt:    item.CreatedAt,
		}
	})

	//返回数据
	resp = &types.IntegralWalletRecordResponse{
		AlreadyUse:      decimal.NewFromInt(int64(alreadyUse)).Div(baiDecimal).StringFixed(2),
		IntegralBalance: decimal.NewFromInt(integralWalletInfo.WalletActiveBalance).Div(baiDecimal).StringFixed(2),
		Page: &types.PageResponse{
			Total:           int64(total),
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}

	return resp, nil
}
